<?php
include "header.inc";

if (isset($_POST["name"])) {
	$programs = array();
	foreach ($_POST as $name=>$value)
		if (strlen($name)>8 && substr($name,0,8)=="program_")
			array_push($programs, substr($name,8));
	if (count($programs)==0) echo "<div style='color:red'>Error: you must select at least one program for the campaign!</div>";
	else {
		require_once "DataBase.inc";
		$res = DataBase::select("selection_campaign", null, array("selection_campaign_name"=>$_POST["name"]));
		if ($res <> false && count($res)>0) echo "<div style='color:red'>Error: a selection campaign already exists with this name!</div>";
		else {
			$id = DataBase::insert("selection_campaign", array("selection_campaign_name"=>$_POST["name"]));
			foreach ($programs as $program_id)
				DataBase::insert("selection_campaign_programs", array("selection_campaign_id"=>$id, "program_id"=>$program_id));
			
			include("exams/create_subjects_in_database.inc");
			create_exams_subjects_in_database($id);
	
			$_SESSION["campaign_id"] = $id;
			$s = "";
			foreach ($programs as $program_id) {
				$r = DataBase::select("program", null, array("program_id"=>$program_id));
				if ($s<>"") $s .= " + ";
				$s .= $r[0]["program_name"];
			}
			$s = $_POST["name"]." (".$s.")";
			$_SESSION["campaign_name"] = $s;
			header('Location: index.php');		
		
			echo "Campaign successfully created.";
			die();
		}
	}
}
?>
<form name='campaign' method='post'>
Name for the new campaign: <input type='text' size=50 maxlength=50 name='name'/><br/>
Please select the programs covered by this campaign:<br/>
<?php
require_once "DataBase.inc";
foreach (DataBase::select("program") as $r)
	echo "<input type='checkbox' name='program_".$r["program_id"]."'/> ".$r["program_name"]."<br/>"; 
?>
<button type='submit'>Create</button>
</form>
<?php 
include "footer.inc"; 
?>